var util = require('../../utils/util.js');
const app = getApp();
Page({

  data: {
    avatarUrl: '',
    nickName: '',
    uid: wx.getStorageSync('userinfo').uid,
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    Custom: app.globalData.Custom,
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    TabCur: 0,
    scrollLeft: 0,
    infoArray: {
      name: '',
      major: '',
      Class: '',
      reward_points: ''
    },
    name: '',
    major: '',
    Class: '',
    qrCode: '',
    lid: '',
    screenWidth: wx.getSystemInfoSync().windowWidth,
    // 扫描结果
    result: '',
    endTime: '',
    // 日历
    onCalendar: false,
    recordList: [],
    recordLen: '',
    listDate: '今日签到',
    // 含有签到列表的当前月的日期
    dateList: [],
    unsignlist: [],
    unsign_len: 0,
    launch_len: 0,
    faceExistFlag: true,
    tmp: '',
  },
  onLoad: async function (options) {
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      uid: wx.getStorageSync('userinfo').uid,
      style: [{
        month: 'current',
        day: new Date().getDate(),
        color: 'white',
        background: '#728eff'
      }],
      avatarUrl: wx.getStorageSync('avatarInfo').avatarUrl,
      nickName: wx.getStorageSync('userinfo').name,
      createTime: util.formatDate(new Date()),
    })

    // 个人信息
    new Promise(async (resolve, reject) => {
      await wx.User.getUserInfo()
      resolve(wx.getStorageSync('userinfo'))
    }).then(res => {
      this.data.infoArray.name = res.name
      this.data.infoArray.major = res.major
      this.data.infoArray.Class = res.Class
      this.data.infoArray.reward_points = res.reward_points
      this.setData({
        userinfo: res,
        infoArray: this.data.infoArray,
      })
      wx.hideLoading({
        success: (res) => {},
      })
    })
    // 获取当前月的有签到列表的日期
    await this.selectRecordByMonth(util.formatMonth(new Date()))
    this.setData({
      recordLen: wx.getStorageSync('recordList').length,
      recordList: wx.getStorageSync('recordList')
    })
    var Time = util.formatTime(new Date());
    await wx.User.selectMyRecord({
      data: {
        uid: this.data.uid,
        date: util.formatDate(new Date())
      }
    })
    this.setData({
      unsignlist: wx.getStorageSync('MyRecord'),
      unsign_len: wx.getStorageSync('MyRecord').length,
    })
    wx.stopPullDownRefresh()
    //当前日期
    const timestamp = Date.parse(new Date());
    const date = new Date(timestamp);
    const Y = date.getFullYear();
    const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    wx.setStorageSync('createTime', Y + '-' + M + '-' + D)
  },

  getUserProfile(e) {
    var that = this
    wx.getUserProfile({
      desc: '用于获取用户头像', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        if (res.userInfo != null) {
          wx.setStorageSync('avatarInfo', res.userInfo)
          app.globalData.userInfo = res.userInfo
          wx.login({
            success: res => {
              var code = res.code
              new Promise(async (resolve, reject) => {
                await wx.User.login({
                  url: "/auth/login",
                  data: {
                    code: code,
                    userAvatar: wx.getStorageSync('avatarInfo').avatarUrl,
                    userAlias:wx.getStorageSync('avatarInfo').nickName
                  }
                })
                resolve(wx.getStorageSync('userinfo').type)
              }).then(res => {
                that.setData({
                  avatarUrl: wx.getStorageSync('avatarInfo').avatarUrl,
                  nickName: wx.getStorageSync('userinfo').name
                })
              })
            }
          })
        }
      }
    })
  },

  // 帮助
  // toHelp: async function () {
  //   wx.navigateTo({
  //     url: '../help/help',
  //   })

  // },


  onShow: async function () {
    // await wx.User.checkFaceExist({
    //   data: {
    //     uid: this.data.uid
    //   }
    // })
    wx.hideHomeButton();
    await wx.User.getUserInfo()
    this.data.infoArray.name = wx.getStorageSync('userinfo').name
    this.data.infoArray.major = wx.getStorageSync('userinfo').major
    this.data.infoArray.Class = wx.getStorageSync('userinfo').Class
    this.data.infoArray.reward_points = wx.getStorageSync('userinfo').reward_points
    this.setData({
      userinfo: wx.getStorageSync('userinfo'),
      infoArray: this.data.infoArray,
      avatarInfo: wx.getStorageSync('userinfo').avatar,
      nickName: wx.getStorageSync('userinfo').name,
    })
    await wx.User.selectRecord({
      data: {
        uid: this.data.uid,
        date: this.data.createTime,
      }
    })
    await wx.User.selectMyRecord({
      data: {
        uid: this.data.uid,
        date: util.formatDate(new Date())
      }
    })
    this.setData({
      unsignlist: wx.getStorageSync('MyRecord'),
      unsign_len: wx.getStorageSync('MyRecord').length,
      recordLen: wx.getStorageSync('recordList').length,
      recordList: wx.getStorageSync('recordList')
    })
  },
  onReFresh: function () {
    this.onShow()
  },
  changebar(e) {},

  // 点击日历事件
  dayClick: async function (event) {
    const year = event.detail.year;
    const month = event.detail.month;
    if (month < 10) {
      this.data.month = '0' + month;
    } else {
      this.data.month = month;
    }
    if (event.detail.day < 10) {
      this.data.day = '0' + event.detail.day;
    } else {
      this.data.day = event.detail.day;
    }
    this.data.createTime = year + '-' + this.data.month + '-' + this.data.day
    wx.setStorageSync('createTime', this.data.createTime)
    await wx.User.selectRecord({
      data: {
        uid: wx.getStorageSync('userinfo').uid,
        date: this.data.createTime
      }
    })
    await wx.User.selectMyRecord({
      data: {
        uid: wx.getStorageSync('userinfo').uid,
        date: this.data.createTime
      }
    })
    var style = [];
    //先把含有签到的日期设置颜色
    style.push({
      month: 'current',
      day: event.detail.day,
      color: 'white',
      background: '#728EFF'
    })
    for (let i = 0; i < this.data.dateList.length; i++) {
      if (this.data.dateList[i] != event.detail.day) {
        style.push({
          month: 'current',
          day: this.data.dateList[i],
          color: 'white',
          background: '#00B26A'
        })
      }
    }
    this.setData({
      style: style,
      listDate: month + '月' + this.data.day + '日',
      unsignlist: wx.getStorageSync('MyRecord'),
      unsign_len: wx.getStorageSync('MyRecord').length,
      recordList: wx.getStorageSync('recordList'),
      recordLen: wx.getStorageSync('recordList').length
    })
  },
  // 日历组件点击显示和隐藏
  transmit() {
    if (this.data.onCalendar == false) {
      this.setData({
        onCalendar: true
      })
      if (wx.pageScrollTo) {
        wx.pageScrollTo({
          scrollTop: 0,
        })
      }
    } else {
      this.setData({
        onCalendar: false
      })
    }
  },

  // 积分商城
  recordShop: function () {
    wx.navigateTo({
      url: '../products/products?reward_points=' + this.data.infoArray.reward_points,
    })
  },

  gotonowpoint(e) {
    wx.navigateTo({
      url: '/pages/student/scan_faceActive?lid=' + e.currentTarget.dataset.lid + '&location_x=' + e.currentTarget.dataset.locax + '&location_y=' + e.currentTarget.dataset.locay + '&rangement=' + e.currentTarget.dataset.range,
    })
  },

  // 切换月份
  changeMonth: async function (e) {
    const year = e.detail.currentYear
    if (e.detail.currentMonth < 10) {
      this.setData({
        tmp: '0' + e.detail.currentMonth
      })
    } else {
      this.setData({
        tmp: e.detail.currentMonth
      })
    }
    const date = year + '-' + this.data.tmp
    await this.selectRecordByMonth(date)
  },
  // 点击日历标题
  monthChange: async function (e) {
    const year = e.detail.currentYear
    const month = e.detail.currentMonth
    const date = year + '-' + month
    await this.selectActivityByMonth(date)
  },
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop
    });
  },
  // 去排行榜页面
  gotoRank() {
    wx.navigateTo({
      url: '/pages/student/ranklist',
    })
  },
  // 去排行榜页面
  gotoFriend() {
    wx.navigateTo({
      url: '/pages/student/friendlist',
    })
  }, 

  getScancode: function () {
    var _this = this;
    if (wx.getStorageSync('userinfo').type == null) {
      wx.showModal({
        title: '提示',
        content: "请先在 我的页面内 登录！", //提示内容
        confirmColor: '#0ABF53', //确定按钮的颜色
        success(res) {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/student/home',
            })
          } else if (res.cancel) {
          }
        }
      })
    } else {
      // 只允许从相机扫码
      wx.scanCode({
        onlyFromCamera: true,
        success: (res) => {
          this.setData({
            code: res.result
          })
          wx.setStorageSync('lid', this.data.lid)
          wx.User.scanCode({
            data: {
              code: this.data.code
            }
          })
        }
      })
    }

  },
  // 列表详情点击跳转页面
  showDetail: function (e) {
    wx.navigateTo({
      url: './listDetail?lid=' + e.currentTarget.dataset.lid + '&title=' + e.currentTarget.dataset.title,
    })
  },
  // 修改信息
  updateUserInfo: function () {
    // 跳转到修改信息页面
    wx.navigateTo({
      url: '../teacher/sign_changeInfo',
    })
  },

  // 每日任务
  onDailyTask: function () {
    wx.navigateTo({
      url: '../dailyTask/dailyTask',
    })
  },

  //意见反馈
  // feedback: function() {
  //   wx.navigateTo({
  //     url: '../feedback/feedback',
  //   })
  // },
  //关于
  about:function(){
    wx.navigateTo({
      url: '../student/about',
    })
  },

  // 点击切换身份
  changeType: async function () {
    await wx.User.userTypeAlter({
      data: {
        uid: wx.getStorageSync('userinfo').uid,
        type: 1
      }
    })
  },

  // 返回一个月中含有签到列表的日期
  selectRecordByMonth: async function (e) {
    await wx.User.selectRecordByMonth({
      data: {
        uid: wx.getStorageSync('userinfo').uid,
        month: e
      }
    })
    this.setData({
      dateList: wx.getStorageSync('stuDateList'),
    })
    let style = new Array;
    for (let i = 0; i < this.data.dateList.length; i++) {
      style.push({
        month: 'current',
        day: this.data.dateList[i],
        color: 'white',
        background: '#00B26A'
      });
    }
    if (e.substring(0, 4) == wx.getStorageSync('createTime').substring(0, 4) && e.substring(5, 7) == wx.getStorageSync('createTime').substring(5, 7)) {
      style.push({
        month: 'current',
        day: parseInt(wx.getStorageSync('createTime').substring(8, 10)),
        color: 'white',
        background: '#728eff'
      })
    }
    this.setData({
      style
    });
  },

  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60
    })
  },
})